package com.gs.disk.modules.headImgAndWallper.dao.mobile;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gs.common.mapper.CommonMapper;
import com.gs.common.util.ConvertUtils;
import com.gs.disk.modules.headImgAndWallper.dto.ResourceDto;
import com.gs.disk.modules.headImgAndWallper.entity.CategoryEntity;
import com.gs.disk.modules.headImgAndWallper.entity.ResourceEntity;
import com.gs.disk.service.common.MinioService;
import org.apache.ibatis.annotations.Mapper;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;


@Mapper
public interface MobileResourceDao extends CommonMapper<ResourceEntity, ResourceEntity> {


    /**
     * 获取所有资源列表
     * @param categoryId
     * @return
     */
    default Map<String, List<ResourceDto>> resourceListMap(Long categoryId, Long page, Long limit) {
        // 获取资源列表
        List<ResourceDto> resourceDtoList = ConvertUtils.sourceToTarget(resourceList(categoryId, page, limit), ResourceDto.class);
        Map<String, List<ResourceDto>> map = new HashMap();
        resourceDtoList.forEach(r -> {
            String categoryIdKey = Convert.toStr(r.getCategoryId());

            List<ResourceDto> categoryList = map.get(categoryIdKey);

            // 不存在就创建, 存在就添加
            if(ObjectUtil.isNull(categoryList)) {
                List<ResourceDto> list = new ArrayList();
                list.add(r);
                map.put(categoryIdKey, list);
            }else {
                ((List)categoryList).add(r);
                map.put(categoryIdKey, categoryList);
            }
        });
        return map;
    }


    /**
     * 所有资源中的最大排序
     * @return
     */
    default Integer getMaxSort() {
        Integer currentSort = get("select max(sort) max_sort from wallper_resource", Integer.class);


        if(ObjectUtil.isNull(currentSort)) return null;

        return currentSort + 1;
    }

    /**
     * 获取资源列表
     * @param categoryId
     * @return
     */
    default List<ResourceEntity> resourceList(Long categoryId, Long page, Long limit) {
        QueryWrapper<ResourceEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id, category_id,category_name, oss_file_id, thumbnail_file_id, sort");

        if(ObjectUtil.isNotEmpty(categoryId)) {
            wrapper.eq("category_id", categoryId);
        }

        wrapper.orderByDesc("sort");
        return this.selectPage(new Page(page, limit), wrapper)
                .getRecords();
    }
}
